﻿using System;
using System.Diagnostics;
using System.Text;
using Plugins.Interfaces;

namespace Plugins.Samples.Internal
{
    static class PiAlgorithm
    {
        /// <summary> 
        /// Calculates a given number of hexadecimal digits of PI from the given start position. 
        /// </summary> 
        /// <param name="start">Hexadecimal position to start calculating hexadecimal digits from.</param> 
        /// <param name="length">Number of hexadecimal digits to calculate. Needs to be multiple of 10.</param> 
        /// <returns>Requested hexadecimal digits of PI.</returns> 
        public static string Calculate(IPluginWorkItem workItem, PiChildWindow window, int start, int length)
        {
            if (start < 0)
                throw new ArgumentException("start");

            if (length < 0 || length % 10 != 0)
                throw new ArgumentException("length");

            // 
            // Calculate in chunks of 10 given our precision. 
            // 


            StringBuilder result = new StringBuilder();
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int pos = start; pos < start + length; pos += 10)
            {
                if (!(workItem == null || workItem.IsRunAsync)) break;
                double val = 4 * Pi.Sum(1, pos) - 2 * Pi.Sum(4, pos) - Pi.Sum(5, pos) - Pi.Sum(6, pos);
                val = val - (int)val + 1;
                result.Append(Pi.ToHex(val));
            }
            stopwatch.Stop();
            window.AddWatch(stopwatch.ElapsedMilliseconds);
            return result.ToString();
        }
    }
}
